﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Xml;

namespace SimpleText.Framework
{

	public class TextDefinition
	{
		public TextDefinition()
		{
			Texts = new Dictionary<string, Text>();
		}

		public string Name { get; set; }
		public string Comment { get; set; }
		public string TranslatorComment { get; set; }
		public string Source { get; set; }

		public Dictionary<string, Text> Texts { get; set; }

		/// <summary>
		/// String indexer (uses the language short name)
		/// </summary>
		public Text this[string languageShortName]
		{
			get
			{
				if (Texts.ContainsKey(languageShortName))
				{
					return Texts[languageShortName];
				}
				else
				{
					return null;
				}				
			}
			set
			{
				Texts[languageShortName] = value;
			}
		}

		public void InitWithXml(XmlNode xmlNode)
		{
			Name = xmlNode.Attributes["name"].Value;
			XmlNode commentNode = xmlNode.SelectSingleNode("comment");
			XmlNode translatorCommentNode = xmlNode.SelectSingleNode("translatorComment");
			XmlNode sourceNode = xmlNode.SelectSingleNode("source");
			if (commentNode != null)
			{
				Comment = commentNode.InnerText;
			}
			if (translatorCommentNode != null)
			{
				TranslatorComment = translatorCommentNode.InnerText;
			}
			if (sourceNode != null)
			{
				Source = sourceNode.InnerText;
			}
			foreach (XmlNode textNode in xmlNode.SelectNodes("text"))
			{
				Text newText = new Text();
				newText.InitWithXml(textNode);
				Texts[newText.LanguageShortName] = newText;
			}
		}

		public string GetAsXml()
		{
			return GetAsXml("");
		}
		public string GetAsXml(string baseIndent)
		{
			string indent = "\t";

			string xml = "";
			xml += baseIndent + "<textDefinition name=\"" + Name + "\">" + "\r\n";
			if (!String.IsNullOrEmpty(Comment))
			{
				xml += baseIndent + indent + "<comment><![CDATA[" + Comment + "]]></comment>" + "\r\n";
			}
			if (!String.IsNullOrEmpty(TranslatorComment))
			{
				xml += baseIndent + indent + "<translatorComment><![CDATA[" + TranslatorComment + "]]></translatorComment>" + "\r\n";
			}
			if (!String.IsNullOrEmpty(Source))
			{
				xml += baseIndent + indent + "<source><![CDATA[" + Source + "]]></source>" + "\r\n";
			}
			foreach (Text text in Texts.Values)
			{
				xml += text.GetAsXml(baseIndent + "\t") + "\r\n";
			}
			xml += baseIndent + "</textDefinition>" + "\r\n";
			return xml;
		}
	}
}